package com.clgk.wechatmall.freemarker;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.alibaba.fastjson.JSON;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class AutoTableFreemarker implements ApplicationListener<ContextRefreshedEvent> {
	
	private static Logger logger = LoggerFactory.getLogger(AutoTableFreemarker.class);
	
	private static Map<String, String> urlMap = new HashMap<String, String>();
	
	private static Map<String,Object> languageMap = new HashMap<String, Object>();
	
	/**
	 * 项目路径下的文件夹
	 */
//	private static String rootfileurl="F:"+File.separator+"study"+File.separator+"test"+File.separator+"test-web"+File.separator+"src"
//							+File.separator+"main"+File.separator+"java"+File.separator+"com"+File.separator+"clgk"+File.separator+"test";
	
	/**录入信息 begin*/
	
	//生成文件地址
	private static String url = "jdbc:mysql://120.24.237.124:3306/lampserver";//数据库地址
	private static String username="root";//数据库账户名
	private static String password = "444e47a405" ;//数据库密码
	
	private static String rootfileurl="G:"+File.separator+"study"+File.separator+"meiyuan"+File.separator+"JAVAProject"+File.separator+"lampserver"
										+File.separator+"lampserver-core"+File.separator+"src"+File.separator+"main"+File.separator+"java"+File.separator
										+"com"+File.separator+"mykj"+File.separator+"lamp";
	private static String rootpackage="com.mykj.lamp.";//包前缀
	private static String module="DeviceData";//类名模块前缀
	
	private static String schema="lampserver";//库
	private static String table="T_DEVICE_DATA";//表
	
	
	/**录入信息 end*/
	
	private static String moduleLow=module.toLowerCase();
	
	static {
		urlMap.put(("action.ftl"),rootfileurl + File.separator + moduleLow + File.separator +"action" + File.separator + (module + "Action.java"));
		urlMap.put("vo.ftl",rootfileurl + File.separator + moduleLow + File.separator +"bean" + File.separator + (module + "Bean.java"));
		urlMap.put("service.ftl",rootfileurl + File.separator + moduleLow + File.separator +"service" + File.separator + module + "Service.java");
		urlMap.put("serviceimpl.ftl",rootfileurl + File.separator + moduleLow + File.separator +"service" + File.separator + "impl" + File.separator + module + "ServiceImpl.java");
		urlMap.put("dao.ftl",rootfileurl + File.separator + moduleLow + File.separator +"dao" + File.separator + module + "Dao.java");
		urlMap.put("daoimpl.ftl",rootfileurl + File.separator + moduleLow + File.separator +"dao" + File.separator + "impl" + File.separator + module + "DaoImpl.java");
		
		languageMap.put("rootpackage", rootpackage);
		languageMap.put("module", module);
		languageMap.put("tablename", schema + "." + table);
		languageMap.put("moduleLow", moduleLow);
	}
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
//		initI18nUrl();
//		initLanguage();
		initI18n();
	}
	
	public void load(){
		try {
			String sql = "SELECT m.`COLUMN_NAME` columnname,m.`DATA_TYPE` datatype,m.`COLUMN_COMMENT` columncomment,m.`COLUMN_TYPE` columntype,m.`COLUMN_KEY` columnkey";
			sql += " FROM information_schema.columns m ";
			sql += " WHERE table_schema = '"+schema+"' ";
			sql += " AND table_name = '"+table+"' ";
			Class.forName("com.mysql.jdbc.Driver") ;
//			String url = "jdbc:mysql://dev-mysql.hoinnet.com:1234/test" ;
//			String username = "root" ;
//			String password = "tcloudpasswd" ;
			Connection con =
					DriverManager.getConnection(url , username , password ) ;
			Statement stmt = con.createStatement() ;
			ResultSet rs = stmt.executeQuery(sql) ;
//			int count = rs.getRow();
			List<ColumnVo> list = new ArrayList<ColumnVo>();
			while(rs.next()){
//				ResultSetMetaData metaData = rs.getMetaData();
//				int columnCount = metaData.getColumnCount();
				ColumnVo c = new ColumnVo();
				c.setColumncomment(rs.getString("columncomment"));
				c.setColumnkey(rs.getString("columnkey"));
				c.setColumnname(rs.getString("columnname"));
				c.setColumntype(rs.getString("columntype"));
				c.setDatatype(rs.getString("datatype"));
				list.add(c);
//				for(int i = 1;i <= columnCount; i++){
//					System.out.print(rs.getString(i) + ":");
//				}
//				System.out.println();
			}
			System.out.println(JSON.toJSONString(list));
			languageMap.put("cloumnlist", list);
			
			sql = " SELECT table_name NAME,TABLE_COMMENT tablecomment  ";
			sql += " FROM INFORMATION_SCHEMA.TABLES  ";
//			sql += " WHERE table_type='base table'  ";
			sql += " WHERE table_schema = '"+schema+"' ";
			sql += " AND table_name = '"+table+"' ";
			rs = stmt.executeQuery(sql) ;
			languageMap.put("tablecomment", "");
			if(rs.next()){
				languageMap.put("tablecomment", rs.getString("tablecomment"));
			}
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();
			}
			if(con != null){
				con.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
//	/**
//	 * 加载国际化文件地址
//	 */
//	@SuppressWarnings("unchecked")
//	public void initI18nUrl(){
//		try {
//			ClassLoader loader = Thread.currentThread().getContextClassLoader();
//			URL url = loader.getResource("i18n"+File.separator+"i18nurl.xml");
//			SAXBuilder sb = new SAXBuilder();
//			Document doc = sb.build(url);
//			Element root = doc.getRootElement();
//			rootfileurl = root.getAttribute("rootfileurl").getValue();
//			rootfileurl = rootfileurl == null || rootfileurl.trim() == "" ? "" : rootfileurl.trim() + File.separator;
//			List<Element> list = root.getChildren("module");
//			for(Element ele : list){
//				String value = ele.getAttribute("fileurl").getValue();				
//				List<Element> list2 = ele.getChildren("url");
//				List<String> keys = new ArrayList<String>();
//				for(Element u : list2){
//					keys.add(u.getTextTrim());
//				}
//				urlMap.put(value, keys);
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//		}
//	}
	
	public static void main(String[] args) {
//		new I18nFreemarker().load();
		try {
//			ClassLoader loader = Thread.currentThread().getContextClassLoader();
//			System.out.println(loader.getResource("/").getPath());
			
			
//			String path = AutoTableFreemarker.class.getResource("").getPath()+File.separator+"ftl";
//			System.out.println(path);
			AutoTableFreemarker i18nFreemarker = new AutoTableFreemarker();
			i18nFreemarker.load();
			i18nFreemarker.initI18n();
			
			
//			File f = new File("src/main/resources/i18n/language");
//			String[] list = f.list();
//			if(list == null){
//				return;
//			}
//			
//			for(String s :list){
//				String filename = s.split("\\.")[0];
//				InputStream in = loader.getResourceAsStream(s);  
//				Properties prop = new Properties();  
//				prop.load(in);  
//				Enumeration<Object> keys = prop.keys();
//				Map<String, String> map = new HashMap<String, String>();
//				while(keys.hasMoreElements()){
//					String key = keys.nextElement().toString();
//					map.put(key, prop.getProperty(key));
//				}
//				languageMap.put(filename, map);
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
//	/**
//	 * 加载国际化语言
//	 */
//	public void initLanguage(){
//		try {
//			String path = this.getClass().getResource("/").getPath();
//			
//			File f = new File(path + File.separator + "i18n" + File.separator + "language");
//			File[] listFiles = f.listFiles();
//			if(listFiles == null){
//				return;
//			}
//			for(File file :listFiles){
//				String filename = file.getName().split("\\.")[0];
//				Reader reader = new InputStreamReader(new FileInputStream(file));  
//				Properties prop = new Properties();  
//				prop.load(reader);  
//				Enumeration<Object> keys = prop.keys();
//				Map<String, String> map = new HashMap<String, String>();
//				while(keys.hasMoreElements()){
//					String key = keys.nextElement().toString();
//					map.put(key, prop.getProperty(key));
//				}
//				languageMap.put(filename, map);
//			}
//		} catch (Exception e) {
//			logger.error(e.getMessage(),e);
//		}
//	}
	
	/**
	 * 生成国际化文件
	 */
	public void initI18n(){
		Configuration cfg = new Configuration();
		Writer out = null;
		try {
			
			Set<String> urlSet = urlMap.keySet();
			if(urlSet == null){
				return;
			}
			
			String path = this.getClass().getResource("").getPath()+File.separator+"ftl";
			
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setEncoding(Locale.getDefault(), "UTF-8");
			/**
			 * 国际化文件KEY
			 */
			for(String fileName : urlSet){
				Template template = cfg.getTemplate(fileName,"UTF-8");
				
//				Map<String, String> map = null;
				String fileUrl = urlMap.get(fileName);
				File file = new File(fileUrl.substring(0,fileUrl.lastIndexOf("\\")));
				file.mkdirs();
				
				out = new OutputStreamWriter(new FileOutputStream(fileUrl)); 
				template.setEncoding("UTF-8");
				template.process(languageMap, out);
			}
			
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				logger.error(e.getMessage(),e);
			}
		}
	}
}
